package server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.TimerTask;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;


	/**
	 * This class will hold a scheduled task.
	 */
	public class SchedTask extends TimerTask{
		
		private int taskType;
		private Scheduler scheduler;

		/**
		 * Constructor for SchedTask class.
		 * This class will self-call at pre-determined time
		 * @param task - Task to perform on wake up
		 */
		public SchedTask(int task,Scheduler scheduler){
			
			this.taskType = task;
			this.scheduler = scheduler;
		}

		/**
		 * Will call this function upon wake up
		 */
		public void run(){

			switch(taskType){
				
			case Scheduler.DAILY_TASKS:{
				DailyTasks();
				break;
			}
			case Scheduler.WEEKLY_TASKS:{
				WeeklyTasks();
				break;
			}
			
			}
			
		}
		
		
		
		public void DailyTasks(){
			BookController bookController = new BookController(scheduler.server, scheduler.DB);
			MessageController messageController = new MessageController(scheduler.server, scheduler.DB);
			
			Calendar today = Calendar.getInstance();
			today.add(Calendar.DAY_OF_MONTH, 1);
			String currDate = today.get(Calendar.YEAR) + "-";
			if (today.get(Calendar.MONTH) < 10) currDate += "0" + (today.get(Calendar.MONTH) + 1) + "-";
			else currDate += (today.get(Calendar.MONTH) + 1) + "-";
			if (today.get(Calendar.DAY_OF_MONTH) < 10) currDate += "0" + today.get(Calendar.DAY_OF_MONTH);
			else currDate += today.get(Calendar.DAY_OF_MONTH);
			
			String query = "SELECT * FROM loans WHERE RETURN_DATE = '" + currDate +"';";
			ResultSet rs = scheduler.DB.Query(query);
			String title="OBL Reminder !!!";
			String Msg ="You need to return a Book tomorrew";

			try {
				while(rs.next())
				{
					String mail = bookController.GetMailForMember(rs.getInt("UID"));
					messageController.SendMail(mail,Msg,title);
					try {
						messageController.masendmail();
					} catch (AddressException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (MessagingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			} catch (SQLException e) {
				// TODO handle this error
				
			}

		}
		
		public void WeeklyTasks(){
			ReportController reportController = new ReportController(scheduler.server, scheduler.DB);
			reportController.BuildActivityReports();
			
		}

}
